﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Mvc;
using System.Web.Routing;
using System.Collections.Specialized;
using System.Web;
using MyLib.Util;
using Tasks.Common.Enum;
using Tasks.Common;

namespace Tasks.Core
{
    public enum PageNavStyle
    {
        /// <summary>
        /// 网址式的导航
        /// </summary>
        Url,
        /// <summary>
        /// 表单形式的导航
        /// </summary>
        Form
    }

    /// <summary>
    /// 分页扩展方法
    /// </summary>
    public static class HtmlHelpers
    {

        #region "字符处理"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static MvcHtmlString DisplayToolTips(this HtmlHelper helper, string tip1,string tip2)
        {
            if(string.IsNullOrWhiteSpace(tip1) && string.IsNullOrWhiteSpace(tip2)) 
                return null;

            string html = " <a href=\"\"><span class=\"tool tooltipsIcon\"><span class=\"tip\">{0}</span></span></a>";

            if (!string.IsNullOrWhiteSpace(tip1) && string.IsNullOrWhiteSpace(tip2))
            {
                html = string.Format(html, tip1);
            }
            else if (string.IsNullOrWhiteSpace(tip1) && !string.IsNullOrWhiteSpace(tip2))
            {
                html = string.Format(html, tip2);
            }
            else{
                html = string.Format(html, tip1 + "<br/>" + tip2);
            }

            return MvcHtmlString.Create(html);
        }

        /// <summary>
        /// 给数字加上+-符号
        /// </summary>
        /// <param name="dec"></param>
        /// <returns></returns>
        public static MvcHtmlString NumberAppendSymbol(this HtmlHelper helper, decimal dec)
        {
            string str = "";
            if (dec < 0)
                str = "<span class=\"minus\">-</span>" + Math.Abs(dec);
            else if (dec > 0)
                str = "<span class=\"positive\">+</span>" + Math.Abs(dec);
            else
                str = dec.ToString();

            return MvcHtmlString.Create(str);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static MvcHtmlString StrToHtml(this HtmlHelper helper, string str)
        {
            return MvcHtmlString.Create(StringUtil.CharToHtml(str));
        }

        #endregion

        #region "分页"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="name"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static string MetaTags(this HtmlHelper helper, string name, string msg)
        {
            //返回meta标签
            return string.Format("<meta name=\"{0}\" content=\"{1}\"/>", name, msg);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <param name="prefixUrl"></param>
        /// <param name="style"></param>
        /// <returns></returns>
        public static MvcHtmlString RenderUrlPageNav(this HtmlHelper htmlHelper, int currentPageIndex, int pageSize, int recordCount, string prefixUrl)
        {
            if (recordCount == 0) return null;

            PageNavStyle style = PageNavStyle.Url;
            int pageCount = (recordCount % pageSize == 0 ? recordCount / pageSize : recordCount / pageSize + 1);
            string pageUrl = "";
            //拼接参数
            string urlParameter = "PageIndex=#PageIndex#";

            NameValueCollection collection = HttpContext.Current.Request.QueryString;
            string[] keys = collection.AllKeys;
            for (int i = 0; i < keys.Length; i++)
            {
                if (keys[i] != "PageIndex")
                    urlParameter += string.Format("&{0}={1}", keys[i], collection[keys[i]]);
            }

            prefixUrl = prefixUrl == "" ? HttpContext.Current.Request.Url.AbsoluteUri : prefixUrl;

            if (prefixUrl.IndexOf("?") != -1)
                pageUrl = prefixUrl.Substring(0, prefixUrl.IndexOf("?") + 1) + urlParameter;
            else
                pageUrl = prefixUrl + "?" + urlParameter;


            StringBuilder sb = new StringBuilder();
            //sb.AppendFormat("总共{0}条记录,共{1}页,当前第{2}页&nbsp;&nbsp;", recordCount, pageCount, currentPageIndex);
            if (currentPageIndex == 1)
                sb.Append("<span  class='text_step'>首页</span>&nbsp;");
            else
            {
                string url1 = GetPageUrl(style, pageUrl, 1);
                sb.AppendFormat("<a href={0} class='su su_scroll'>首页</a>&nbsp;", url1);
            }
            if (currentPageIndex > 1)
            {
                string url1 = GetPageUrl(style, pageUrl, currentPageIndex - 1);
                sb.AppendFormat("<a href={0}  class='su su_scroll'>上一页</a>&nbsp;", url1);
            }
            else
                sb.Append("<span  class='text_step'>上一页</span>&nbsp;");


            //中间需要页
            int navStartIndex = currentPageIndex % 5 == 0 ? currentPageIndex - 4 : currentPageIndex - currentPageIndex % 5 + 1;
            int navEndIndex = currentPageIndex % 5 == 0 ? currentPageIndex : currentPageIndex + (5 - currentPageIndex % 5);
            navEndIndex = navEndIndex > pageCount ? pageCount : navEndIndex;

            for (int i = navStartIndex; i <= navEndIndex; i++)
            {
                if (i == currentPageIndex)
                    sb.AppendFormat("<span><em><i></i></em><i></i><b>{0}</b><i></i><em><i></i></em></span>", i);
                else
                {
                    string url1 = GetPageUrl(style, pageUrl, i);
                    sb.AppendFormat("<a href={0} class='su su_scroll'>{1}</a>&nbsp;", url1, i);
                }
            }


            //下一页
            if (currentPageIndex < pageCount)
            {
                string url1 = GetPageUrl(style, pageUrl, currentPageIndex + 1);
                sb.AppendFormat("<a href={0} class='su su_scroll'>下一页</a>&nbsp;", url1);
            }
            else
                sb.Append("<span   class='text_step'>下一页</span>&nbsp;");

            if (currentPageIndex == pageCount)
                sb.Append("<span  class='text_step'>末页</span>&nbsp;");
            else
            {
                string url1 = GetPageUrl(style, pageUrl, pageCount);
                sb.AppendFormat("<a href={0}  class='su su_scroll'>末页</a>&nbsp;", url1);
            }

            return MvcHtmlString.Create(sb.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="urlFormat"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public static string GetPageUrl(PageNavStyle style, string urlFormat, int pageIndex)
        {
            if (style == PageNavStyle.Url)
                return urlFormat.Replace("#PageIndex#", pageIndex.ToString());
            else
                return string.Format("javascript:pager({0});", pageIndex);
        }

        /// <summary>
        /// 暂时分页导航栏
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalRecordCount"></param>
        /// <param name="urlFormat">Url 参数格式 如：url/?PageIndex=#PageIndex#& ……</param>
        /// <returns></returns>
        public static MvcHtmlString RenderPageNav(this HtmlHelper htmlHelper, int currentPageIndex, int pageSize, int recordCount, string urlFormat, PageNavStyle style)
        {
            if (recordCount == 0) return null;

            int pageCount = (recordCount % pageSize == 0 ? recordCount / pageSize : recordCount / pageSize + 1);


            NameValueCollection collection = HttpContext.Current.Request.QueryString;
            string[] keys = collection.AllKeys;
            for (int i = 0; i < keys.Length; i++)
            {
                if (keys[i] != "PageIndex")
                    urlFormat += string.Format("&{0}={1}", keys[i], collection[keys[i]]);
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("总共{0}条记录,{2}/{1}&nbsp;&nbsp;", recordCount, pageCount, currentPageIndex);
            if (currentPageIndex == 1)
                sb.Append("<span>首页</span>&nbsp;");
            else
            {
                string url1 = GetPageUrl(style, urlFormat, 1);
                sb.AppendFormat("<span><a href={0}>首页</a></span>&nbsp;", url1);
            }
            if (currentPageIndex > 1)
            {
                string url1 = GetPageUrl(style, urlFormat, currentPageIndex - 1);
                sb.AppendFormat("<span><a href={0}>上一页</a></span>&nbsp;", url1);
            }
            else
                sb.Append("<span>上一页</span>&nbsp;");


            if (currentPageIndex < pageCount)
            {
                string url1 = GetPageUrl(style, urlFormat, currentPageIndex + 1);
                sb.AppendFormat("<span><a href={0}>下一页</a></span>&nbsp;", url1);
            }
            else
                sb.Append("<span>下一页</span>&nbsp;");

            if (currentPageIndex == pageCount)
                sb.Append("<span>末页</span>&nbsp;");
            else
            {
                string url1 = GetPageUrl(style, urlFormat, pageCount);
                sb.AppendFormat("<span><a href={0}>末页</a></span>&nbsp;", url1);
            }

            sb.AppendFormat("行数:<input id='PageSize' name='PageSize' value='{0}' style='width:40px'/>", pageSize);

            //把提交脚本加入字符串
            if (style == PageNavStyle.Form)
            {
                sb.AppendFormat("<input id='PageIndex' name='PageIndex' type='hidden' value='{0}' />", currentPageIndex);
                sb.Append(@"
                <input id='btnSubmitByNav' type='submit' value='分页' style='display:none;' />
                <script type=""text/javascript"">
                function pager(pageIndex){
                    document.getElementById('PageIndex').value = pageIndex;
                    document.getElementById('btnSubmitByNav').click();
                }    
                </script>
                ");

            }

            return MvcHtmlString.Create(sb.ToString());
        }

        /// <summary>
        /// This is a simple HTML Helper which truncates a string to a given length
        /// </summary>
        /// <param name="helper">HTML Helper being extended</param>
        /// <param name="input">Input string to truncate</param>
        /// <param name="length">Max length of the string</param>
        /// <returns></returns>
        public static string Truncate(this HtmlHelper helper, string input, int length)
        {
            if (string.IsNullOrEmpty(input)) return input;

            if (input.Length <= length)
            {
                return input;
            }
            else
            {
                return input.Substring(0, length) + "...";
            }
        }

        /// <summary>
        /// 下拉框扩展
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <returns></returns>
        public static MvcHtmlString DropDownListExt(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<ul class='ulOption' id='ul{0}'>", name);

            string value = "";
            foreach (var item in selectList)
            {
                if (item.Selected)
                    value = item.Value;

                sb.AppendFormat("<li class='{3}'><a href=\"javascript:void(0)\" onclick=\"selectedOption('{1}','{2}',true);\">{0}</a></li>",
                    item.Text == "" ? "全部" : item.Text,
                    name,
                    item.Value,
                    item.Value == value ? "selected" : "");
            }

            sb.Append("</ul>");
            sb.AppendFormat("<input type='hidden' id='{0}' name='{0}' value='{1}'/>", name, value);

            return MvcHtmlString.Create(sb.ToString());
        }

        public static MvcHtmlString OutputMessage(this HtmlHelper htmlHelper, string message)
        {
            return OutputMessage(htmlHelper, message, MessageType.Alert);
        }

        /// <summary>
        /// 输错提示信息
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="message"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static MvcHtmlString AlertMessage(this HtmlHelper htmlHelper, string title, string message, MessageType messageType, int timeout)
        {
            if (string.IsNullOrEmpty(message))
                return null;
            else
            {
                string icon = "";
                switch (messageType)
                {
                    case MessageType.Alert:
                        icon = "alert";
                        break;
                    case MessageType.attention:
                        icon = "attention";
                        break;
                    case MessageType.correct:
                        icon = "correct";
                        break;
                    case MessageType.error:
                        icon = "error";
                        break;
                    case MessageType.quest:
                        icon = "quest";
                        break;
                    default:
                        icon = "alert";
                        break;
                }

                string js = string.Format("$.Msg.alert('{0}','{1}',{2},'{3}');", title, message, timeout, icon);
                return MvcHtmlString.Create(js);
            }
        }

        /// <summary>
        /// 输错提示信息
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static MvcHtmlString OutputMessage(this HtmlHelper htmlHelper, string message, MessageType messageType)
        {
            if (string.IsNullOrEmpty(message))
                return null;
            else
            {
                string icon = "";
                switch (messageType)
                {
                    case MessageType.Alert:
                        icon = "alert";
                        break;
                    case MessageType.attention:
                        icon = "attention";
                        break;
                    case MessageType.correct:
                        icon = "correct";
                        break;
                    case MessageType.error:
                        icon = "error";
                        break;
                    case MessageType.quest:
                        icon = "quest";
                        break;
                    case MessageType.close:
                        message = "<script>parent.closeCurrentTab();</script>";
                        break;
                    default:
                        icon = "alert";
                        break;
                }

                message = string.Format("<div class='actMessage {1}' id='actMessage'>{0}</div>", message, icon);
                return MvcHtmlString.Create(message);
            }
        }

        #endregion

        /// <summary>
        /// 输错提示信息
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static MvcHtmlString OutputNavigation(this HtmlHelper htmlHelper, string title)
        {
            return OutputNavigation(htmlHelper, title, PageResult.cancel);

        }

        /// <summary>
        /// 输错提示信息
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static MvcHtmlString OutputNavigation(this HtmlHelper htmlHelper, string title, PageResult pageResult)
        {
            string dialogresult = pageResult.ToString();

            string html = @"<div class=""navTitle"">
                <div class=""title"">
                <ul>
                    <li class=""Home SecondLast""><a href=""#"">
                        <div class=""HomeIcon"">
                        </div>
                        <font>{0}</font></a></li>
                </ul>
                </div>
                <div class=""button"">
               <a href=""javascript:void(0)"" onclick='$.Dialog.closeWindow({{""dialogresult"": ""{1}"", ""data"": """" }})'>
                    <img src=""/images/no48x48 24-bit.png"" alt="""" border=""0"">
                </a>            
                </div>
            </div>";

            html = string.Format(html, title, pageResult);

            return MvcHtmlString.Create(html);

        }
    }


}
